import { createRouter, createWebHashHistory } from 'vue-router'
import login from "@/views/LoginPage.vue"
import layout from "@/views/LayoutPage.vue"
import reg from "@/views/RegPage.vue"
import {useUser} from "@/stores/user"
import { showConfirmDialog } from 'vant'

const router = createRouter({
  history: createWebHashHistory(),
  routes:[
    {
      name:'登录',
      path:"/login",
      component:login
    },
    {
      name:'注册',
      path:"/reg",
      component:reg
    },
    {
      path:"/detail",
      name:"详情页",
      component:()=>import("@/views/DetailPage.vue")
    },
    {
      name:'首页',
      path:"/layout",
      component:layout,
      redirect:"/layout/home",
      children:[
        {
          path:"/layout/home",
          name:"首页",
          component:()=>import("@/views/HomePage.vue")
        },
        {
          path:"/layout/category",
          name:"分类",
          component:()=>import("@/views/CategoryPage.vue")
        },
        {
          path:"/layout/cart",
          name:"购物车",
          component:()=>import("@/views/CartPage.vue"),
          meta:{
            requireLogin:true
          }
        },
        {
          path:"/layout/my",
          name:"我的",
          component:()=>import("@/views/MyPage.vue"),
          meta:{
            requireLogin:true
          }
        },
      ]
    },
    
  ]
})

router.beforeEach((to,from)=>{
  let user=useUser()
  if(to.meta.requireLogin){
    if(!user.token){
      showConfirmDialog({
        message: '当前没有登录',
        confirmButtonText: '去登录',
        confirmButtonColor: 'blue'
        // confirm:(){}
      }).then(() => {
        router.push('/login')
      })
      .catch(() => {
      })
      return false
    }
  }
  return
})


export default router
